<template>
    <div>
    </div>
</template>
<script>
import CodeBox from "@/utils/api.js";
import axios from 'axios';

const API = 'https://plugin.coderbox.cn/download-proxy'
//const API = 'http://127.0.0.1:8085'
export default {
  name: "my-plugin",
  components: {},
  data() {
    return {}
  },
  computed: {
    userId() {
      return (CodeBox.user || {}).id
    }
  },
  watch: {},
  mounted() {
    this.loadData()
  },
  methods: {
    loadData() {
      axios.get(API + '/downloadProxy/tasks?userId=' + this.userId).then(res => {
        const data = res.data
        this.list = data.data
        this.list.forEach(v => {
          v.retrieveProgress = null
          if (v.status === 2) {
            this.loopTask(v.taskId)
          }
        })
      })
    },
    addTask() {
      if (!this.url) {
        return
      }
      axios.post(API + '/downloadProxy/addTask', {
        url: this.url,
        userId: this.userId
      }).then(res => {
        this.$notify.success('任务已添加')
        this.loadData()
        this.loopTask(res.data.data.taskId)
        this.url = null
      }).catch(e => {
        this.$notify.error('任务添加失败')
      })
    },
    reAddTask(data) {
      axios.post(API + '/downloadProxy/addTask', {
        url: data.downloadUrl,
        userId: this.userId,
        enabledSt: false
      }).then(res => {
        this.$notify.success('任务已添加')
        this.loadData()
        this.loopTask(res.data.data.taskId)
        this.url = null
      }).catch(e => {
        this.$notify.error('任务添加失败')
      })
    },
    cancel(data) {
      axios.post(API + '/downloadProxy/cancelTask?taskId=' + data.taskId).then(res => {
        if (res.code === 0) {
          this.$notify.success('任务已取消')
        }
      })
    },
    loopTask(taskId) {
      const timer = setInterval(() => {
        axios.get(API + '/downloadProxy/taskStatus?taskId=' + taskId).then(res => {
          const task = res.data.data
          for (let i = 0; i < this.list.length; i++) {
            if (this.list[i].taskId === taskId) {
              this.$nextTick(() => {
                this.list[i] = res.data.data
              })
              break
            }
          }
          if (task.status === 0) {
            this.$notify.success('下载完成，现在你可以取回文件')
          }
          if (task.status === 0) {
            clearInterval(timer)
          }
        })
      }, 1000)
      this.timers.push(timer)

    },
    async download(data) {
      const url = data.retrieveUrl
      const path = await CodeBox.dialog.save(data.fileName)
      if (!path) {
        data.retrieveProgress = null
        return
      }
      data.retrieveProgress = 0
      let last = 0
      CodeBox.fs.download(url, path).then(async id => {
        const unlisten = await CodeBox.event.listen('download_progress', event => {
          let payload = event.payload
          let retrieveProgress = payload.message


          if (payload.id === id) {
            if (retrieveProgress - last >= 0.01) {
              data.retrieveProgress = payload.message
              last = retrieveProgress
            }
            if (retrieveProgress >= 1 && !data.retrieveSuccess) {
              data.retrieveProgress = null
              data.retrieveSuccess = true
              this.$notify.success('取回成功')
              unlisten()
            }
          }
        })

      })

    },
    renderSize: (filesize, fixed) => {
      if (!filesize) {
        return "0 B";
      }
      let unitArr = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
      let index = 0;
      let srcsize = parseFloat(filesize);
      index = Math.floor(Math.log(srcsize) / Math.log(1024));
      let size = srcsize / Math.pow(1024, index);
      size = size.toFixed(fixed || 2);
      return size + ' ' + unitArr[index];
    },
  },
  beforeUnmount() {
    this.timers.forEach(v => {
      clearInterval(v)
    })
  }
}
</script>
<style scoped>
:deep(.el-button.is-text) {
    padding: 0;
}

:deep(.el-descriptions__label) {
    width: 80px;
}


</style>
